<template>
  <div class="hotel-management-container">
    <el-card class="box-card">
      

      <!-- 搜索和操作区域 -->
      <div class="operation-area">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="关键字">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入酒店名称/电话/邮箱"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>

        <div class="action-buttons">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增酒店
          </el-button>
          <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon>批量删除
          </el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="序号" width="80" />
        <el-table-column prop="name" label="酒店名称" width="100" />
        <el-table-column prop="description" label="描述" width="100" />
        <el-table-column prop="address" label="地址" width="100" />
        <el-table-column prop="city" label="城市" width="100" />
        <el-table-column prop="state" label="区" width="100" />
        <el-table-column prop="overallRating" label="评分" width="100" />
        <el-table-column prop="reviewCount" label="评论数" width="100" />
        <el-table-column prop="checkInTime" label="入住时间" width="100" />
        <el-table-column prop="checkOutTime" label="退房时间" width="100" />
        <el-table-column prop="createdAt" label="创建时间" width="100" />
        <el-table-column prop="updatedAt" label="更新时间" width="100" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="hotelFormRef"
        :model="hotelForm"
        :rules="hotelRules"
        label-width="120px"
      >
        <el-form-item label="酒店名称" prop="name">
          <el-input v-model="hotelForm.name" placeholder="请输入酒店名称" />
        </el-form-item>
        <el-form-item label="酒店描述" prop="description">
          <el-input v-model="hotelForm.description" placeholder="请输入酒店描述" />
        </el-form-item>
        <el-form-item label="酒店地址" prop="address">
          <el-input v-model="hotelForm.address" placeholder="请输入酒店地址" />
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="hotelForm.city" placeholder="请输入城市" />
        </el-form-item>
        <el-form-item label="区/县" prop="state">
          <el-input v-model="hotelForm.state" placeholder="请输入区/县" />
        </el-form-item>
        <el-form-item label="评价分数" prop="overallRating">
          <el-input v-model="hotelForm.overallRating" placeholder="请输入评价分数" />
        </el-form-item>
        <el-form-item label="评论数" prop="reviewCount">
          <el-input v-model="hotelForm.reviewCount" placeholder="请输入评论数" />
        </el-form-item>
        <el-form-item label="开始登记入住时间" prop="checkInTime">
          <el-input v-model="hotelForm.checkInTime" placeholder="请输入开始登记入住时间" />
        </el-form-item>
        <el-form-item label="开始登记退房时间" prop="checkoutTime">
          <el-input v-model="hotelForm.checkOutTime" placeholder="请输入开始登记退房时间" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import axios from 'axios'

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedIds = ref([])

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(false)
const hotelFormRef = ref()
const hotelForm = reactive({
   id: 0,
      name: "",
      description: "",
      address: "",
      city: "",
      state: "",
      overallRating: 0,
      reviewCount: 0,
      checkInTime: "",
      checkOutTime: "",
      createdAt: "",
      updatedAt: "",
})

// 表单验证规则
const hotelRules = reactive({
  name: [{ required: true, message: '请输入酒店名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入酒店描述', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  city: [{ required: true, message: '请输入城市', trigger: 'blur' }],
  state: [{ required: true, message: '请输入区/县', trigger: 'blur' }],
  overallRating: [{ required: true, message: '请输入评分', trigger: 'blur' }],
  reviewCount: [{ required: true, message: '请输入评论数', trigger: 'blur' }],
  checkInTime: [{ required: true, message: '请输入入住时间', trigger: 'blur' }],
  checkOutTime: [{ required: true, message: '请输入退房时间', trigger: 'blur' }],
})

// 根据状态返回标签类型
const statusTagType = (status) => {
  switch (status) {
    case '已通过':
      return 'success'
    case '已拒绝':
      return 'danger'
    default:
      return 'warning'
  }
}

// 获取酒店数据
const fetchHotelData = (isSearch = false) => {
  loading.value = true;
  const api = isSearch ? '/hotels/search' : '/api/hotels/page';

  axios.get(api, {
    params: {
      page: pagination.currentPage,
      size: pagination.pageSize,
      keyword: isSearch ? searchForm.keyword : undefined
    }
  })
  .then(response => {
    tableData.value = response.data.records || [];
    pagination.total = response.data.total || 0;
  })
  .catch(error => {
    ElMessage.error('获取数据失败: ' + error.message);
  })
  .finally(() => {
    loading.value = false;
  });
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchHotelData(true); // true 表示是搜索操作
};

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchHotelData()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchHotelData()
}

// 表格选择项改变
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增酒店
const handleAdd = () => {
  isAdd.value = true; // 标记为新增操作
  dialogTitle.value = '新增酒店';

  // 重置表单
  Object.keys(hotelForm).forEach(key => {
    if (key === 'price') {
      hotelForm[key] = 0;
    } else if (key === 'status') {
      hotelForm[key] = '待审核';
    } else {
      hotelForm[key] = '';
    }
  });

  dialogVisible.value = true; // 显示对话框
};

// 编辑酒店
const handleEdit = (row) => {
  isAdd.value = false
  dialogTitle.value = '编辑酒店'
  Object.keys(hotelForm).forEach(key => {
    hotelForm[key] = row[key]
  })
  dialogVisible.value = true
}

// 删除酒店
const handleDelete = (id) => {
  ElMessageBox.confirm('确认删除该酒店吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await axios.delete(`/api/chapter03/hotels/${id}`);
      ElMessage.success(res.data || '删除成功');
      fetchHotelData();
    } catch (error) {
      ElMessage.error(error.response?.data || '删除失败');
    }
  }).catch(() => {});
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }

  ElMessageBox.confirm(`确认删除选中的${selectedIds.value.length}条记录吗?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await axios.put('/api/chapter03/hotels/delete', selectedIds.value);
      ElMessage.success(res.data || '批量删除成功');
      selectedIds.value = [];
      fetchHotelData();
    } catch (error) {
      ElMessage.error(error.response?.data || '批量删除失败');
    }
  }).catch(() => {});
};

// 提交表单
const submitForm = () => {
  hotelFormRef.value.validate(valid => {
    if (valid) {
      if (isAdd.value) {
        // 新增操作
        axios.post('/api/chapter03/hotels', hotelForm)
          .then(() => {
            ElMessage.success('新增成功');
            dialogVisible.value = false;
            pagination.currentPage = 1;
            fetchHotelData();
          })
          .catch(() => {
            ElMessage.error('新增失败');
          });
      } else {
        // 编辑操作
        axios.put(`/api/chapter03/hotels/${hotelForm.id}`, hotelForm)
          .then(() => {
            ElMessage.success('编辑成功');
            dialogVisible.value = false;
            fetchHotelData();
          })
          .catch(() => {
            ElMessage.error('编辑失败');
          });
      }
    }
  });
};

// 图片上传成功
const handleAvatarSuccess = (res) => {
  // 增强容错判断
  if (res && res.url) {
    hotelForm.avatar = res.url;
  } else if (res && res.data && res.data.url) {
    hotelForm.avatar = res.data.url;
  } else {
    ElMessage.error('图片上传失败，数据格式异常');
    console.error('Upload response error:', res);
  }
};

// 图片上传前校验
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 初始化加载数据
onMounted(() => {
  fetchHotelData()
})
</script>

<style scoped>
.hotel-management-container {
  padding: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.operation-area {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

.action-buttons {
  margin-left: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
el-table-column{
  height: 40px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>